//
//  ZMNetworkingManager.swift
//  ZMWeiboSwift
//
//  Created by pg on 2017/7/23.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit
import AFNetworking

//网络请求类型
enum RequestType {
    case get
    case post
}


class ZMNetworkingManager: AFHTTPSessionManager {

    
    //提供全局访问点  单例
    static let sharedManager : ZMNetworkingManager = {
       
        let instance = ZMNetworkingManager()
        
        //添加支持服务器端发送的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/html")
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //设置网络支持非安全类型的https
        //允许无效的https证书
        instance.securityPolicy.allowInvalidCertificates = true
        //不验证域名
        instance.securityPolicy.validatesDomainName = false
        
        
        return instance
    }()
    
    //封装get和post请求方法
    func request(type: RequestType ,urlStr: String,params: Any?,progress:((Progress)->())?,finsishCallBack:  (@escaping (Any?,Error?)->())){
        
        if type == .get{
            
            self.get(urlStr, parameters: params, progress: { (progres: Progress) in
                progress?(progres)
                
            }, success: { (dataTask, response: Any?) in
                
                finsishCallBack(response,nil)
                
              }, failure: { (_ , error) in
                
                finsishCallBack(nil,error)
              })
            
        }else{
            
            self.post(urlStr, parameters: params, progress: { (pro : Progress) in
                progress?(pro)
                
            }, success: { (dataTask, response) in
                
                finsishCallBack(response,nil)
                
            }, failure: { (dataTask, error) in
                
                finsishCallBack(nil ,error)
            })
            
        }
        
        
        
    }
    
    
}

//MARK:- OAuth授权相关接口
extension ZMNetworkingManager {
    
    func requestAccessToken(code: String,callBack: @escaping((Any?, Error?) -> ())){
        
        let urlstring = "https://api.weibo.com/oauth2/access_token"
        //请求参数
        let parmas: [String : Any] = [
            "client_id" : OAuthKey,
            "client_secret" : AppSecret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
            
            
        ]
        //按照文档发送POST请求
        request(type: .post, urlStr: urlstring, params: parmas, progress: nil, finsishCallBack: callBack)
        
        
    }
    
    //根据令牌请求用户信息
    func requestUserInfo(access_token: String,uid: Int64, callBack: @escaping(Any?,Error?)->()){
        //  接口地址
        let urlStr = "https://api.weibo.com/2/users/show.json"
        //  接口参数
        let params: [String: Any] = [
            "access_token": access_token,
            "uid": uid
        ]
        
     //   print(urlStr + "?access_token=\(access_token)&uid=\(uid)")
        
        //  加载网络请求
        request(type: .get, urlStr: urlStr, params: params, progress: nil, finsishCallBack: callBack)
    }
   
    
    
}
//微博相关接口
extension ZMNetworkingManager{
    
    //MARK:- 获取当前登录用户机器所关注的用户的最新微博数据
    func requestStatuses(token: String,max_id:Int64 = 0,sinceId: Int64 = 0,finishedCallBack: @escaping(Any?,Error?)->()){
        
        let urlstr = "https://api.weibo.com/2/statuses/home_timeline.json"
        //请求参数
        let params: [String:Any] = [
            "access_token" : token,
            "since_id" : sinceId,//若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
            "max_id" : max_id,//若指定此参数，则返回ID小于或等于max_id的微博，默认为0
            "count" : 20,//单页返回的记录条数，最大不超过100，默认为20
            "page" : 1 ,  //返回结果的页码，默认为1
            "feature" : 0 //过滤类型ID，0：全部、1：原创、2：图片、3：视频、4：音乐，默认为0
            
        ]
        //发送网络请求
       print(urlstr + "?access_token=\(token)")
       request(type: .get, urlStr: urlstr, params: params, progress: nil, finsishCallBack: finishedCallBack)
        
    }
}


